package com.xbongbong.formula.qlexpress.operator.date;

import com.ql.util.express.Operator;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 计算一个时间段在某年内的相交天数
 * @author 吴峰
 * @version v1.0
 * @date 2019/8/5 10:47
 * @since v1.0
 */
public class OperatorOneYearRangDay extends Operator {


    public OperatorOneYearRangDay(String name){
        this.name = name;
    }

    public OperatorOneYearRangDay(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }


    /**
     * ONEYEARRANGDAY（计算一个时间段在某年内的相交天数）
     * 计算一个时间段在某年内的相交天数
     * 用法：ONEYEARRANGDAY(开始日期, 结束日期, 某一年)
     * ONEYEARRANGDAY(start_timestamp,end_timestamp, year)
     * 计算一个时间段在某年内的相交天数
     * end_timestamp: 必需。结束日期。
     * start_timestamp: 必需。起始日期。
     * year: 年份 必需
     * @return
     * @throws Exception
     */
    @Override
    public Object executeInner(Object[] list) throws XbbException {
        if (Objects.isNull(list) || list.length != BasicConstant.THREE) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        if (list[0] == null || StringUtils.equals(list[0].toString(), Constant.ZERO_STRING)) {
            return null;
        }
        if (list[1] == null || StringUtils.equals(list[1].toString(), Constant.ZERO_STRING)) {
            return null;
        }
        Integer year = Integer.valueOf(list[2].toString());
        Long startTime = PaasDateUtil.getInt(list[0]);
        Long endTime = PaasDateUtil.getInt(list[1]);
        Integer startYear = DateTimeUtil.getYear4Someday(startTime);
        // 获取结束日期的年份
        Integer endYear = DateTimeUtil.getYear4Someday(endTime);
        if (!Objects.equals(startYear, year) && !Objects.equals(endYear, year)) {
            return 0;
        } else if (endYear > year) {
            String date = year + "-" + "12-31 00:00:00";
            endTime = DateTimeUtil.getInt(date, DateTimeUtil.SDF);
        }
        int result = DateTimeUtil.betweenDays(startTime, endTime);
        return Math.abs(result);
    }
}
